package com.wf.smartcomm.server.websocket;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import com.google.gson.Gson;
import com.sun.swing.internal.plaf.metal.resources.metal_zh_TW;
import com.wf.smartcomm.server.bean.UnitMachine;
import com.wf.smartcomm.server.model.CustomWebSocket;
import com.wf.smartcomm.server.model.SocketMessage;
import com.wf.smartcomm.server.service.UnitMachService;
import com.wf.smartcomm.server.util.ConstantUtils;

public class SmartcommServer extends WebSocketServer {
	
	private UnitMachService unitMachService;

	public SmartcommServer() throws UnknownHostException {
		super();
	}
	
	public SmartcommServer(Integer port,UnitMachService unitMachService)throws UnknownHostException{
		super(new InetSocketAddress(port));
		this.unitMachService = unitMachService;
	}
	
	@Override
	public void onClose(WebSocket webSocket, int arg1, String arg2, boolean arg3) {
		System.out.println("onclose -----> " + webSocket.getRemoteSocketAddress().getAddress().getHostAddress());
		unitMachService.delete(ClientSocketPool.clientPool.get(webSocket));
		ClientSocketPool.removeClient(webSocket);
	}

	@Override
	public void onError(WebSocket webSocket, Exception exception) {
		exception.printStackTrace();
		ClientSocketPool.removeClient(webSocket);
	}

	@Override
	public void onMessage(WebSocket webSocket, String message) {
		SocketMessage socketMessage = new Gson().fromJson(message, SocketMessage.class);
		if (socketMessage.getMessageType().equals(ConstantUtils.SOCKET_MSGTYPE_HEARTBEAT)) {
			webSocket.send(message);
			return;
		}else if(socketMessage.getMessageType().equals(ConstantUtils.SOCKET_MSGTYPE_NOTIFY)){
			System.out.println("new message -----> "+message);
			ClientSocketPool.sendMessage(socketMessage.getClientId(), message);
		}else {
			System.out.println("new message -----> "+message);
			ClientSocketPool.saveClient(webSocket, socketMessage.getClientId());
			if (!socketMessage.getClientId().equals("WebBrowserClient")) {
				if (unitMachService.getByHardId(socketMessage.getClientId()) == null) {
					UnitMachine unitMachine = new UnitMachine();
					unitMachine.setHardwareId(socketMessage.getClientId());
					unitMachService.save(unitMachine);
				}
			}
		}
	}

	@Override
	public void onOpen(WebSocket webSocket, ClientHandshake arg1) {
		
	}

}
